package com.concurrent.sample.business.listener;

import com.concurrent.sample.business.consts.BusinessConsts;
import com.concurrent.sample.business.consts.enums.BusinessSwitchEnum;
import com.concurrent.sample.business.dto.CashFlowMessageDTO;
import com.concurrent.sample.business.listener.event.CashFlowEvent;
import com.concurrent.sample.business.manager.CashFlowManagerService;
import com.concurrent.sample.business.service.CashFlowService;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.aop.interceptor.AsyncExecutionAspectSupport;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Slf4j
public class CashFlowEventListener {

  private final CashFlowService cashFlowService;

  private final CashFlowManagerService cashFlowManagerService;

  private final RedissonClient redissonClient;

  @Async(value = AsyncExecutionAspectSupport.DEFAULT_TASK_EXECUTOR_BEAN_NAME)
  @EventListener
  public void handleCashFlowEvent(CashFlowEvent event) {
//    log.info("event = {}", JsonUtils.toJson(event));
    CashFlowMessageDTO message = event.getCashFlowMessageDTO();
    BusinessSwitchEnum businessSwitchEnum = Optional.of(message.getBusinessSwitchFlag())
        .orElse(BusinessConsts.BUSINESS_SWITCH_FLAG);
    switch (businessSwitchEnum){
      case DIRTY_READ:
        cashFlowService.saveWithIncremental(message);
        break;
      case LOCK:
        cashFlowManagerService.saveByLock(message);
        break;
      case MEMORY:
        cashFlowManagerService.saveByMemory(message);
        break;
      default:
        throw new RuntimeException("not support");
    }
  }

}
